package com.example.communitypro.service.impl;

import com.example.communitypro.mapper.*;
import com.example.communitypro.pojo.CommunityInformation;
import com.example.communitypro.pojo.Post;
import com.example.communitypro.pojo.UserInformation;
import com.example.communitypro.service.CommentService;
import com.example.communitypro.service.LabelRelationService;
import com.example.communitypro.service.PostService;
import com.example.communitypro.util.LikeAndCollecionUtil;
import com.example.communitypro.util.ReportAndActionsUtil;
import com.example.communitypro.util.result.Result;
import javafx.geometry.Pos;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class PostServiceImpl implements PostService {
    @Autowired(required=false)
    private PostMapper postMapper;

    @Autowired(required=false)
    private UserActionsMapper userActionsMapper;

    @Autowired(required=false)
    private UserLikesMapper userLikesMapper;

    @Autowired(required=false)
    private UserCollectionMapper userCollectionMapper;

    @Autowired(required=false)
    private CommunityInformationMapper communityInformationMapper;

    @Autowired(required=false)
    private CommentMapper commentMapper;

    @Autowired(required=false)
    private CommentService commentService;
    @Autowired(required=false)
    private LabelRelationMapper labelRelationMapper;




    @Override
    public Result addPost(Post record){
        try {
            System.out.println(record);
            record.setPostClickNumber(0);
            record.setPostCollectionNumber(0);
            record.setPostCommentNumber(0);
            record.setPostLikeNumber(0);
            record.setPostStatus(1);
            if (postMapper.insertSelective(record)>0)
            {
                CommunityInformation communityInformation=communityInformationMapper.selectByPrimaryKey(record.getCommunityNo());
                Integer now = communityInformation.getCommunityPostNumber()+1;
                communityInformation.setCommunityPostNumber(now);
                communityInformationMapper.updateByPrimaryKeySelective(communityInformation);
                return Result.ok().message("新增帖子信息成功").data("postNo",record.getPostNo());
            }
            else{
                return Result.error().message("新增帖子信息失败");
            }
        }catch (Exception e){
            return Result.error().message("新增帖子信息失败");
        }
    }


    @Override
    public Result dropPost(Integer postNo){
        try {
            if(postMapper.selectByPrimaryKey(postNo)!=null)
            {
                Post post = postMapper.selectByPrimaryKey(postNo);
                CommunityInformation communityInformation = communityInformationMapper.selectByPrimaryKey(post.getCommunityNo());
                Integer now = communityInformation.getCommunityPostNumber()-1;
                communityInformation.setCommunityPostNumber(now);
                communityInformationMapper.updateByPrimaryKeySelective(communityInformation);
                labelRelationMapper.deleteByObNo(postNo);
                postMapper.deleteByPrimaryKey(postNo);

                return Result.ok().message("删除帖子信息成功");
            }
            else{
                return Result.error().message("删除帖子信息失败");
            }
        }catch (Exception e){
            return Result.error().message("删除帖子信息失败");
        }
    }

    @Override
    public Result modifyPost(Post record){
        try {
            if(postMapper.updateByPrimaryKeySelective(record)>0)
            {
                return Result.ok().message("修改成功");
            }
            else{
                return Result.error().message("修改失败：未找到对应记录");
            }
        }catch (DuplicateKeyException e){
            System.err.println(e);
            return Result.error().message("修改失败：已经存在对应记录");
        }
        catch (Exception e){
            System.err.println(e);
            return Result.error().message("修改失败："+e.toString());
        }
    }

    @Override
    public Result queryPost(Integer postNo){
        try {
            Post post=postMapper.selectByPrimaryKey(postNo);
            if(post!=null)
            {
                return Result.ok().message("查找帖子信息成功").data("post",post);
            }
            else{
                return Result.error().message("查找帖子信息失败");
            }
        }catch (Exception e){
            return Result.error().message("查找帖子信息失败");
        }
    }

    @Override
    public Result queryPostAndUser(Integer postNo,Integer user_no){
        try {
            Post post=postMapper.selectByPrimaryKey(postNo);
            List<Post> posts = new ArrayList<>();
            if(post!=null)
            {
                posts.add(post);
                List<Integer> like = LikeAndCollecionUtil.like(posts,user_no);
                List<Integer> collection = LikeAndCollecionUtil.collecion(posts,user_no);
                return Result.ok().message("查找帖子信息成功").data("post",post).data("like",like).data("collection",collection);
            }
            else{
                return Result.error().message("查找帖子信息失败");
            }
        }catch (Exception e){
            return Result.error().message("查找帖子信息失败");
        }
    }

    @Override
    public Result queryHotCommunityPost(Integer community_no){
        try {
            List<Post> posts=postMapper.getHotCommunityPost(community_no);
            for(int i=0;i<posts.size();i++)
            {
                if (posts.get(i).getPostStatus()==0)
                {
                    posts.remove(i);
                }
            }
            if(posts!=null)
            {
                return Result.ok().message("查找某社区帖子（热度）信息成功").data("posts",posts).count(posts.size());
            }
            else{
                return Result.error().message("查找某社区帖子（热度）信息失败");
            }
        }catch (Exception e){
            return Result.error().message("查找某社区帖子（热度）信息败");
        }
    }

    @Override
    public Result queryCommunityPost(Integer community_no){
        try {
            List<Post> posts=postMapper.getCommunityPost(community_no);
            if(posts!=null)
            {
                return Result.ok().message("查找某社区帖子（时间）信息成功").data("posts",posts).count(posts.size());
            }
            else{
                return Result.error().message("查找某社区帖子（时间）信息失败");
            }
        }catch (Exception e){
            return Result.error().message("查找某社区帖子（时间）信息失败");
        }
    }

    @Override
    public Result queryCommunityPassPost(Integer community_no ,Integer post_status){
        try {
            List<Post> posts=postMapper.getCommunityPassPost(community_no,post_status);
            if(posts!=null)
            {
                return Result.ok().message("得到某社区某种状态下的帖子成功").data("posts",posts).count(posts.size());
            }
            else{
                return Result.error().message("得到某社区某种状态下的帖子失败");
            }
        }catch (Exception e){
            return Result.error().message("得到某社区某种状态下的帖子失败");
        }
    }

    @Override
    public Result queryUserPost(Integer user_no){
        try {
            List<Post> posts=postMapper.getUserPost(user_no);

            if(posts!=null)
            {
                for(int i=0;i<posts.size();i++)
                {
                    if (posts.get(i).getPostStatus()==0)
                    {
                        posts.remove(i);
                    }
                }
                return Result.ok().message("得到某用户所有帖子成功").data("posts",posts).count(posts.size());
            }
            else{
                return Result.error().message("得到某用户所有帖子失败");
            }
        }catch (Exception e){
            return Result.error().message("得到某用户所有帖子失败");
        }
    }

    @Override
    public Result queryPassPost(Integer user_no,Integer post_status){
        try {
            List<Post> posts=postMapper.getPassPost(user_no,post_status);
            if(posts!=null)
            {
                return Result.ok().message("找到某用户某种状态下的帖子成功").data("posts",posts);
            }
            else{
                return Result.error().message("找到某用户某种状态下的帖子失败");
            }
        }catch (Exception e){
            return Result.error().message("找到某用户某种状态下的帖子失败");
        }
    }

    @Override
    public Result queryAllPost() {
        try {
            List<Post> posts=postMapper.getAllPost();

            if(posts!=null)
            {
                for(int i=0;i<posts.size();i++)
                {
                    if (posts.get(i).getPostStatus()==0)
                    {
                        posts.remove(i);
                    }
                }
                return Result.ok().message("找到所有帖子成功").data("posts",posts).count(posts.size());
            }
            else{
                return Result.error().message("找到所有帖子失败");
            }
        }catch (Exception e){
            return Result.error().message("找到所有帖子失败");
        }
    }
    public Result findAllPost(){
        try {
            List<Post> posts=postMapper.getAllPost();

            if(posts!=null)
            {
                return Result.ok().message("找到所有帖子成功").data("posts",posts).count(posts.size());
            }
            else{
                return Result.error().message("找到所有帖子失败");
            }
        }catch (Exception e){
            return Result.error().message("找到所有帖子失败");
        }
    }

    @Override
    public Result queryHotPost() {
        try {
            List<Post> posts=postMapper.getHotPost();
            if(posts!=null)
            {
                return Result.ok().message("找到所有帖子成功").data("posts",posts);
            }
            else{
                return Result.error().message("找到所有帖子失败");
            }
        }catch (Exception e){
            return Result.error().message("找到所有帖子失败");
        }
    }

    @Override
    public Result queryAllPass(Integer post_status) {
        try {
            List<Post> posts=postMapper.getAllPass(post_status);
            if(posts!=null)
            {
                return Result.ok().message("找到所有某状态帖子成功").data("posts",posts);
            }
            else{
                return Result.error().message("找到所有某状态帖子失败");
            }
        }catch (Exception e){
            return Result.error().message("找到所有某状态帖子失败");
        }
    }


    @Override
    public Result find(Integer user_no) {//发现帖子页面
        try {

            List<Post> posts=postMapper.getHotPost();
            List<Post> posts1 = ReportAndActionsUtil.userActions(posts,user_no);//排除举报用户的帖子
            List<Post> posts2 = ReportAndActionsUtil.userReportPost(posts1,user_no);//排除拉黑的帖子
            posts2.removeIf(post -> post.getPostStatus() == 0);
            if( posts2.size()>0 )
            {
                List<Integer> like = LikeAndCollecionUtil.like(posts,user_no);
                List<Integer> collection = LikeAndCollecionUtil.collecion(posts,user_no);
                return Result.ok().message("发现帖子成功").data("posts",posts2).data("like",like).data("likes",like.size()).data("collection",collection).data("collections",collection.size());
            }
            else{
                return Result.error().message("发现帖子失败");
            }
        }catch (Exception e){
            return Result.error().message("发现帖子失败");
        }
    }

    @Override
    public Result recommend(Integer user_no) {//推荐帖子
        List<Post> posts1 = userLikesMapper.getPostLike(user_no);//用户点赞的帖子
        List<Post> posts2 = userCollectionMapper.getPostCollection(user_no);//用户收藏的帖子
        List<CommunityInformation> communityInformations = new ArrayList<>();
        List<CommunityInformation> communityInformations1 = userCollectionMapper.getCommunityCollection(user_no);

        for (Post post1 : posts1) {
            CommunityInformation communityInformation = communityInformationMapper.selectByPrimaryKey(post1.getCommunityNo());
            if (communityInformation != null) {
                communityInformations.add(communityInformation);
            }
        }

        for (Post post2 : posts2) {
            CommunityInformation communityInformation = communityInformationMapper.selectByPrimaryKey(post2.getCommunityNo());
            if (communityInformation != null) {
                communityInformations.add(communityInformation);
            }
        }

        List<Post> posts = new ArrayList<>();
        for (CommunityInformation communityInformation : communityInformations) {
            posts.addAll(postMapper.getHotCommunityPost(communityInformation.getCommunityNo()));
        }

        posts.addAll(postMapper.getHotPost());
        communityInformations1.addAll(communityInformationMapper.findCommunityInformationAll());

        /**
         * 去除重复元素
         * */

        Set<CommunityInformation> set = new LinkedHashSet<>();
        set.addAll(communityInformations1);
        communityInformations1.clear();
        communityInformations1.addAll(set);


        try {
            List<Post> posts11 = ReportAndActionsUtil.userActions(posts,user_no);//排除举报用户的帖子
            List<Post> posts22 = ReportAndActionsUtil.userReportPost(posts11,user_no);//排除拉黑的帖子
            posts22.addAll(postMapper.getHotPost());
            Set<Post> set2 = new LinkedHashSet<>();
            set2.addAll( posts22);
            posts22.clear();
            posts22.addAll(set2);
            List<Integer> like = LikeAndCollecionUtil.like(posts,user_no);
            List<Integer> collection = LikeAndCollecionUtil.collecion(posts,user_no);
            posts22.removeIf(post -> post.getPostStatus() == 0);
            Collections.shuffle(posts22);
            return Result.ok().message("推荐帖子成功").data("posts",posts22).data("communityInformation",communityInformations1).data("like",like).data("likes",like.size()).data("collection",collection).data("collections",collection.size());
        }catch (Exception e){
            return Result.error().message("推荐帖子失败");
        }
    }

    @Override
    public Result selectPost(String keyword) {
        try {
            List<Post> posts=postMapper.selectPost(keyword);
            if(posts!=null)
            {
                return Result.ok().message("找到关键字帖子成功").data("posts",posts).count(posts.size());
            }
            else{
                return Result.error().message("找到关键字帖子失败");
            }
        }catch (Exception e){
            return Result.error().message("找到关键字帖子失败");
        }
    }

    @Override
    public Result like(Integer user_no) {//关注页面
        List<Post> posts = new ArrayList<>();
        List<UserInformation> userInformations = userActionsMapper.getUserFollow(user_no,1);
        List<CommunityInformation> communityInformations = userLikesMapper.getCommunityLike(user_no);
        communityInformations.addAll(userCollectionMapper.getCommunityCollection(user_no));

        for (UserInformation userInformation : userInformations){
            posts.addAll(postMapper.getUserPost(userInformation.getUserNo()));
        }

        for (CommunityInformation communityInformation : communityInformations){
            posts.addAll(postMapper.getCommunityPost(communityInformation.getCommunityNo()));
        }

        List<Post> posts2 = userCollectionMapper.getPostCollection(user_no);//用户收藏的帖子
        posts.addAll(posts2);

        /**
         * 去除重复元素
         * */



        Set<Post> set = new LinkedHashSet<>();
        set.addAll(posts);
        posts.clear();
        posts.addAll(set);

        /**
        * 排序
        * */

        List<Post> posts1 = posts.stream().sorted(Comparator.comparing(Post::getEndingTime)).collect(Collectors.toList());



        try {
            if( posts1.size() > 0 )
            {
                List<Post> posts11 = ReportAndActionsUtil.userActions(posts1,user_no);//排除举报用户的帖子
                List<Post> posts22 = ReportAndActionsUtil.userReportPost(posts11,user_no);//排除拉黑的帖子
                List<Integer> like = LikeAndCollecionUtil.like(posts,user_no);
                List<Integer> collection = LikeAndCollecionUtil.collecion(posts,user_no);
                posts22.removeIf(post -> post.getPostStatus() == 0);
                Collections.shuffle(posts22);
                return Result.ok().message("找到关注帖子成功").data("posts",posts22).count(posts22.size()).data("like",like).data("likes",like.size()).data("collection",collection).data("collections",collection.size());
            }
            else{
                return Result.error().message("找到关注帖子失败");
            }
        }catch (Exception e){
            return Result.error().message("找到关注帖子失败");
        }
    }


    /**
     *
     * @param date
     * @return
     */
    @Override
    public int countByDate(String date) {
        return postMapper.countByDate(date);
    }
}
